<template>
  <div style="background: #FFFFFF;padding: 15px;">
	  <div style="margin-left: 26px; font-size: 13px; font-weight: bold;">
	  	<span>温湿度实时查询</span>
	  </div>
	  <div style="margin-left: 20px;margin-top: 20px; padding:5px">
	  	<a-row :gutter="16">
	  		<a-col :span="3">
	  			<j-dict-select-tag style="width: 100%" placeholder="请选择车间" v-model="queryParam.workshop"
	  				dictCode="workshop" />
	  		</a-col>
	  		<a-col :span="3">
				  <a-input placeholder="请输入机器名称" v-model="queryParam.deviceName"></a-input>
	  		</a-col>
	  	</a-row>
	  
	  </div>
    <!-- <div>
      <a-select
        :default-value="selectedWorkshop"
        style="width: 200px;float: right;"
        :options="options"
        @change="changeFactory"
      >
      </a-select>
    </div> -->
    <div style="display: flex;margin-top: 20px;width: 100%">
      <div style="width: 35%">
        <a-table :columns="columns" :data-source="tableData" :pagination='false' :customRow="handleRowClick" @change="onChange" :scroll="{ y: 340 }">
          <span slot="temperature" slot-scope="text" style="color: rgb(35, 184, 153)">{{ text }}</span>
          <span slot="humidity" slot-scope="text" style="color: rgb(56, 125, 255)">{{ text }}</span>
        </a-table>
      </div>
      <div style="width: 65%;position:relative;">
		 <a-spin class="spinModal" v-if="isload"/>
        <div id="main" style="height: 400px;width: 90%"></div>
      </div>
    </div>
  </div>
</template>

<script>
import { MWebsocketMixin } from '@/mixins/MWebsocketMixin'
import { getWenShiGroupStateList } from '@/api/customApi'
import * as echarts from 'echarts';
let myChart;
const columns = [
  {
    title: '机器',
    dataIndex: 'deviceName',
    key: 'deviceName',
    width: 150,
	onFilter: (value, record) => record.deviceName.indexOf(value) === 0,
	sorter: (a, b) => a.deviceName.length - b.deviceName.length,
	sortDirections: ['descend'],
  },
  {
    title: '温度',
    dataIndex: 'temperature',
    key: 'temperature',
    width: 150,
    scopedSlots: { customRender: 'temperature' },
	defaultSortOrder: 'descend',
	sorter: (a, b) => a.temperature - b.temperature,
  },
  {
    title: '湿度',
    dataIndex: 'humidity',
    key: 'humidity',
    width: 150,
    scopedSlots: { customRender: 'humidity' },
	defaultSortOrder: 'descend',
	sorter: (a, b) => a.humidity - b.humidity,
  }
]
export default {
  mixins: [MWebsocketMixin],
  components: {},
  data() {
    return {
      tableData: [],
      columns,
      selectedWorkshop: 3,
      firstTime: 1,
      wsEchartsDataState: {},
	  queryParam:{
		  workshop:undefined,
		  deviceName:''
	  },
      isload:true
    }
  },
  mounted() {
    this.queryParam.workshop = this.$store.state.workshopNo ? this.$store.state.workshopNo : 3;
    this.getEchartsData()
  },
  computed: {
    wenShiGroupState() {
      let result;
	  let arr=[];
      if (this.$store.state.socketData.length != 0) {
        result = this.$store.state.socketData.find(item => item.workshop == this.$store.state.workshopNo);
         arr=this.fuzzySearch(result.temperatureHumidity,'deviceName',this.queryParam.deviceName)
      }
      if ( arr.length>0) {
        this.setWenShiGroupStateList(arr[0].id, arr[0].deviceName)
        this.firstTime = -1
      }
      return arr
    }
  },
  watch: {
    wenShiGroupState: {
      immediate: true,
      handler(val) {
        if (val) {
          this.tableData = val
        }
      }
    },
    wsEchartsDataState: {
      immediate: true,
      handler(val) {
        if (val) {
          this.$nextTick(() => {
            this.getEchartsData(val)
          })
        }
      }
    },
	'queryParam.workshop'(newv,oldv) {
		
		this.selectedWorkshop = newv;
		let arr=[];
		if(newv){
			this.$store.commit(
			  'updateWorkshopData',
			  this.$store.state.socketData.find(item => item.workshop == this.selectedWorkshop)
			)
			if(this.$store.state.socketData.length!=0){
				this.$store.commit(
				  'updateWorkshopNo',
				  this.$store.state.socketData.find(item => item.workshop == this.selectedWorkshop).workshop
				)
			}else{
				this.$store.commit(
				  'updateWorkshopNo',''
				)
			}
			
		}
	},
  },
  methods: {
	  //对象数组中根据某个字段模糊搜索
	  fuzzySearch(array, key, searchTerm) {
	    const regExp = new RegExp(searchTerm, 'i');
	      return array.filter(item => regExp.test(item[key]));
	  },
    websocketOnmessage: function(e) {
      let result = JSON.parse(e.data)
      //收到socket后存入所有信息
      this.$store.commit('updateSocketData', result)
      // console.log('socket数据',this.$store.state.socketData)
      // 之后根据当前查看车间存入当前信息
      this.$store.commit(
        'updateWorkshopData',
        this.$store.state.socketData.find(item => item.workshop == this.selectedWorkshop)
      )
      // 存入当前车间号
      this.$store.commit(
        'updateWorkshopNo',
        this.$store.state.socketData.find(item => item.workshop == this.selectedWorkshop).workshop
      )
    },
    getEchartsData(data) {
	  if(!data) return;
      let option = {
        tooltip: {
          trigger: 'axis'
        },
        legend: {
          data: ['温度', '湿度'],
          right: 30
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: data.date
        },
        yAxis: [
          {
            type: 'value',
            axisLabel: {
              formatter: '{value} °C'
            }
          },
          {
            type: 'value',
            min: 0,
            max: 100,
            position: 'right',
            axisLabel: {
              formatter: '{value} %'
            }
          }
        ],
        series: [
          {
            name: '温度',
            type: 'line',
            stack: 'Total',
            data: data.wen
          },
          {
            name: '湿度',
            type: 'line',
            stack: 'Total',
            data: data.shi
          }
        ]
      }
	 // if(myChart==null){
	   	
	 //   }
	  myChart = echarts.init(document.getElementById('main'));
      myChart.setOption(option);
	   window.addEventListener('resize', ()=>{
		   myChart.resize();
	   });
    },
	handleRowClick(record, index){
		return{
			on:{
				click:()=>{
					this.setWenShiGroupStateList(record.id, record.deviceName)
				}
			}
		}
	},
    onChange(val) {
      return {
        on: {
          click: event => {
            this.setWenShiGroupStateList(val.id, val.deviceName)
          }
        }
      }
    },
    //设置图表使用的数组
    setWenShiGroupStateList(id, deviceName) {
      let query = {
        parentId: id,
        pageSize: -1,
		
      }
	  this.isload=true;
      getWenShiGroupStateList(query).then(res => {
        let wsEchartsDataStateRES = {}
        wsEchartsDataStateRES.name = deviceName
        let date = []
        let wen = []
        let shi = []
        res.result.records.forEach(item => {
          date.push(item.time)
          wen.push(item.temperature)
          shi.push(item.humidity)
        });
		 this.isload=false;
        wsEchartsDataStateRES.date = date
        wsEchartsDataStateRES.wen = wen
        wsEchartsDataStateRES.shi = shi
        this.wsEchartsDataState = wsEchartsDataStateRES
      })
    }
  }
}
</script>
<style lang="less" scoped>
	 /deep/ .ant-table-tbody{
		 height:calc(100vh - 100px)
	 }
	 .spinModal{
		 position:absolute;
		 top:45%;
		 left:45%;
	 }
//#main {
//  width: 70%;
//  height: 400px;
//  margin-left:10px;
//}
</style>
